package CSDN;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 手写线程池
 * User: 王圆豪
 * Date: 2025-05-15
 * Time: 14:37
 */

class MyThreadPool{
    /*
    创建一个阻塞队列，作为缓冲区，当队列为空时，调用take的线程会进入阻塞，
    直到队列中传入任务。当队列满时，调用put的线程会进入阻塞，直到队列不为满。
     */
    BlockingQueue<Runnable> q = null;
    public MyThreadPool(int capacity){
        //尽晚的创建
        q = new ArrayBlockingQueue<>(capacity);
        //创建固定数量的线程
        for (int i = 0; i < capacity; i++) {
            Thread thread = new Thread(()->{
                //每个线程都进行无限循环用来捕获队列中的任务
               while (true) {
                   Runnable runnable = null;
                   try {
                       runnable = q.take();
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   runnable.run();
               }
            });
            thread.setDaemon(true);
            thread.start();
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {
        //将任务放入队列
        q.put(runnable);
    }
}

public class Test24 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(10);
        for (int i = 0; i < 10; i++) {
            int id = i;
            myThreadPool.submit(()->{
                System.out.println(Thread.currentThread().getName()+"执行任务"+id);
            });
        }
    }
}
